import * as antdHelper from "./antd-helper";

const fileTypes = {
  video: ["avi", "wmv", "mpeg", "mp4", "m4v", "mov", "asf", "flv", "f4v", "rmvb", "rm", "3gp",
    "webm", "mkv", "vob", "ogv", "ts", "mts", "m2ts", "mxf"],
  music: ["mp3", "wav", "wma", "mp2", "flac", "midi", "ra", "ape", "aac", "cda", "ogg", "m4a",
    "alac", "aiff", "au"],
  image: ["jpeg", "jpg", "png", "svg", "gif", "bmp", "tiff", "webp", "heif", "svg", "ico", "psd", "ai",
    "eps", "raw", "cr2", "nef", "orf", "sr2"],
  app: ["rar", "zip", "7z", "xz", "gz"],
  document: ["docs", "doc", "docx", "xls", "txt", "xlsx", "ppt", "pptx", "pdf", "odt", "ods", "odp", "rtf",
    "md", "tex", "epub", "pages", "key", "numbers","html"],
  zip: [
    "rar", "zip", "7z", "xz", "gz", "tar", "bz2", "tgz", "iso", "z", "lzma",
  ]
};

export function getFileExt(fileName) {
  if (!fileName) return "";
  let tmp = fileName.toLocaleLowerCase().split(".");
  let type = tmp[tmp.length - 1];
  return type;
}
export function getFileType(fileName) {
  let type = getFileExt(fileName);
  for (let k in fileTypes) {
    let arr = fileTypes[k];
    if (arr.includes(type)) {
      return k;
    }
  }
  return "unknow";
}
export function getFileTypeId(fileName) {
  let type = getFileType(fileName);
  let o = {
    'app': 1,
    'video': 2,
    'image': 3,
    'document': 4,
    'unknow': 5,
    'zip': 6,
    'music': 7
  }
  return o[type];
}
export function idToTypeName(id) {
  let arr = ["Unknow", "Applications", "Videos", "Images", "Documents", "Unknow", "Zips", "Musics"];
  return arr[id];
}
export function downloadFile(url, name, size) {
  // console.log("size", JSON.stringify(size,null,2));
  let type = getFileType(name);
  if (type == "image") {
    return downloadImage(url, name);
  } else {
    window.open(url); return;
    var downloadLink = document.createElement("a");
    downloadLink.href = url;
    downloadLink.download = name;
    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
  }
}
export function downloadImage(imgsrc, name) {
  antdHelper.loading("downloading...");
  let image = new Image();
  image.setAttribute("crossOrigin", "anonymous");
  image.onload = function () {
    let canvas = document.createElement("canvas");
    canvas.width = image.width;
    canvas.height = image.height;
    let context = canvas.getContext("2d");
    context?.drawImage(image, 0, 0, image.width, image.height);
    let url = canvas.toDataURL(`image/png`);
    let a = document.createElement("a");
    let event = new MouseEvent("click");
    a.download = name;
    a.href = url;
    a.dispatchEvent(event);
    antdHelper.loading();
  };
  image.src = imgsrc;
}
